package com.yiren.dbaa.module.help_center.api.impl;

import android.app.Activity;
import android.os.Handler;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.yiren.backstage.communication.api.AbstractCommunication;
import com.yiren.backstage.communication.thread.RTKConnection;
import com.yiren.backstage.communication.utils.MessagesUtil;
import com.yiren.backstage.currency.constant.SignalGConstant;
import com.yiren.backstage.currency.utils.FileUtil;
import com.yiren.dbaa.constant.AddressConstant;
import com.yiren.dbaa.constant.G;
import com.yiren.dbaa.constant.StringConstant;
import com.yiren.dbaa.currency.api.CommonCallBack;
import com.yiren.dbaa.net.oss.IOssFileOperationApi;
import com.yiren.dbaa.net.interf.OssFileCallback;
import com.yiren.dbaa.net.oss.impl.OssFileOperationApiImpl;
import com.yiren.dbaa.module.help_center.api.IHardwareUpdate;
import com.yiren.dbaa.module.help_center.bean.DeviceUpdateBean;
import com.yiren.dbaa.module.help_center.api.services.HardwareUpdateService;
import com.yiren.dbaa.module.device.dialog.HardwareUpdateDialog;
import com.yiren.dbaa.module.device.model.DeviceConnectModel;
import com.yiren.dbaa.module.device.util.HardwareUpdatePathUtil;
import com.yiren.dbaa.module.device.view.dialog.DownloadStatusDialog;
import com.yiren.dbaa.view.dialog.LoadDialog;
import com.yiren.dbaa.view.toast.MessageBox;

import org.apache.commons.lang.StringUtils;

import java.io.File;
import java.util.Map;

/**
 * @author lwb
 * @date : 2022/7/26 11:42
 * @description: 硬件更新实现
 */
public class HardwareUpdateImpl implements IHardwareUpdate {

    private Activity activity;
    private IOssFileOperationApi iOssFileOperationApi;
    private boolean isUpdateHand;
    private HardwareUpdateDialog hardwareUpdateDialog;
    private AbstractCommunication abstractCommunication;
    private HardwareUpdateService hardwareUpdateService;
    private DeviceConnectModel  deviceConnectModel;
    private File binFile;            //更新包个数
    private CommonCallBack callBack;


    public HardwareUpdateImpl(Activity activity) {
        this.activity = activity;
        iOssFileOperationApi = new OssFileOperationApiImpl(activity);
        hardwareUpdateDialog = new HardwareUpdateDialog(activity);
        hardwareUpdateService = new HardwareUpdateService(activity);
        deviceConnectModel = new DeviceConnectModel(activity);
    }

    @Override
    public void checkSystemUpdate(boolean isUpdateHand,CommonCallBack callBack) {
        this.isUpdateHand = isUpdateHand;
        this.callBack = callBack;
        if (G.isHardwareUpgrades) {
            ossTxtDownload(AddressConstant.HOST_MACHINE_CONFIG_URL);
        } else {
            String url = getUpgradesInstructions();
            if (!TextUtils.isEmpty(url)) {
                ossTxtDownload(url);
            }else{
                MessageBox.show(activity,"设备连接失败!");
            }
        }


    }

    @Override
    public void updateHardwareVersion(DeviceUpdateBean deviceUpdateBean) {
        if (RTKConnection.getIsNonFourG()) RTKConnection.useCommand = true;
        LoadDialog.show(activity, "正在更新中，请稍后...");
        new Handler().postDelayed(() -> {
            LoadDialog.dismiss(activity);
            if (G.isHardwareUpgrades) {
                downLoadFileProcess(AddressConstant.HOST_MACHINE_PATH, deviceUpdateBean);
            } else {
                String upgradesPath = hardwareUpdateService.getUpgradesPath();
                if (!TextUtils.isEmpty(upgradesPath)) {
                    downLoadFileProcess(upgradesPath, deviceUpdateBean);
                }
            }
        }, 6000);  //这里因为切换到指令模式需要5秒钟，所以延时6秒执行
    }

    private void ossTxtDownload(String objectKey) {
        iOssFileOperationApi.downLoadTxtFile(StringConstant.DJ_APK, objectKey, new OssFileCallback() {
            @Override
            public void success(String result) {
                DeviceUpdateBean deviceUpdateBean = new Gson().fromJson(result, DeviceUpdateBean.class);
                LoadDialog.dismiss(activity);
                // 获取硬件参数信息
                if (null != G.connectDeviceMessage) {
                    int versionCodeByHost = Integer.parseInt(G.connectDeviceMessage.getVersionCodeByHost());
                    if (StringUtils.isNotEmpty(deviceUpdateBean.getVersioncode())) {
                        int versionCode = Integer.parseInt(deviceUpdateBean.getVersioncode());
                        if (versionCodeByHost < versionCode) {
                            if (deviceUpdateBean.isForce()) {    //强制更新
                                updateHardwareVersion(deviceUpdateBean);
                            } else if (deviceUpdateBean.isUpdate()) { //硬件提示更新
                                activity.runOnUiThread(() -> hardwareUpdateDialog.show(deviceUpdateBean, new CommonCallBack() {
                                    @Override
                                    public void complete() {
                                      updateHardwareVersion(deviceUpdateBean);
                                    }
                                }));
                            } else {
                                if (isUpdateHand) {
                                    activity.runOnUiThread(() -> hardwareUpdateDialog.show(deviceUpdateBean, new CommonCallBack() {
                                        @Override
                                        public void complete() {
                                            updateHardwareVersion(deviceUpdateBean);
                                        }
                                    }));
                                } else {
                                    //TODO 非手动更新检测软件更新
                                }
                            }
                            ;
                        } else {
                            if (isUpdateHand) MessageBox.show(activity, "已是最新版本!");
                        }
                    } else {
                        if (isUpdateHand) MessageBox.show(activity, "已是最新版本!");
                    }
                }


            }

            @Override
            public void fail(String error) {

            }
        });


    }

    /**
     * 获取硬件升级服务器说明文件路径
     */
    @Override
    public String getUpgradesInstructions() {
        String hardwareUpgradesInstructions = "";
        if (null != G.connectDeviceMessage) {
            hardwareUpgradesInstructions = HardwareUpdatePathUtil.getConfigObjectKey();
        } else {
            for (Map.Entry<Integer, String> integerStringEntry : SignalGConstant.mapValue.entrySet()) {
                Integer key = integerStringEntry.getKey();
                if (key.equals(MessagesUtil.PARAM)) {
                    String value = integerStringEntry.getValue();
                    G.connectDeviceMessage = deviceConnectModel.analysisDeviceData(value);
                    break;
                }
            }
            if (G.connectDeviceMessage != null) {
                hardwareUpgradesInstructions = HardwareUpdatePathUtil.getConfigObjectKey();
            }
        }
        return hardwareUpgradesInstructions;
    }

    /**
     * 带进度条下载
     */
    private DownloadStatusDialog downloadStatusDialog;
    private void downLoadFileProcess(String hostMachinePath, DeviceUpdateBean deviceUpdateBean) {
        LoadDialog.show(activity, "正在获取版本，请稍后...", false);
        iOssFileOperationApi.downLoadFile(StringConstant.DJ_APK, hostMachinePath + deviceUpdateBean.getApkname(), FileUtil.fetchAvailableSdcardFoloder() + "/yiren/dbaf/hdUpdate/", AddressConstant.HOST_MACHINE_NAME, new OssFileCallback() {

            @Override
            public void contentLength(long total) {
                LoadDialog.dismiss(activity);
                downloadStatusDialog = new DownloadStatusDialog(activity,(int) total);
                activity.runOnUiThread(() -> downloadStatusDialog.show() );
            }

            @Override
            public void progress(int len) {
                activity.runOnUiThread(() -> downloadStatusDialog.refreshProgress(len));
            }

            @Override
            public void success(String result) {
                activity.runOnUiThread(() -> {
                    downloadStatusDialog.close();
                    LoadDialog.show(activity, "正在更新主机程序，请勿关闭电源(否则可能导致主机无法使用)！升级的过程会持续一分钟左右，请耐心等待...", false);
                });

                hardwareUpdateService.hdUpdate(deviceUpdateBean.getApkname(), new CommonCallBack() {
                    @Override
                    public void success(Object result) {
                        if (RTKConnection.getIsNonFourG()) RTKConnection.useCommand = true;
                        MessagesUtil messageRd = new MessagesUtil(MessagesUtil.REBOOT, 0, new byte[0], new byte[0]);
                        hardwareUpdateService.toUpgrade(new CommonCallBack() {
                            @Override
                            public void success(Object result) {
                                String[] split = result.toString().split(";");
                                String version = split[1];
                                String newHost = split[2];
                                if (!version.equals("FAILED")) {
                                    if (newHost.equals("NEWHOST")) {
                                        binFile = new File(FileUtil.fetchAvailableSdcardFoloder() + "/yiren/dbaf/hdUpdate/DiJia1.bin");
                                        hardwareUpdateService.startUpdateNewHost(new CommonCallBack() {
                                            @Override
                                            public void success(Object result) {
                                                LoadDialog.dismiss(activity);
                                                SignalGConstant.isObdUpdating = false;
                                                binFile.delete();  //删除更新包文件
                                                //TODO 检测软件更新

                                                //TODO 设置OBD车型
                                                callBack.success("");
                                                activity.runOnUiThread(() -> hardwareUpdateDialog.showUpdateSuccessDialog(deviceUpdateBean));
                                            }

                                            @Override
                                            public void fail(String error) {
                                                if (StringUtils.isNotEmpty(error))
                                                    activity.runOnUiThread(() ->hardwareUpdateDialog.showUpdateFailDialog(error));
                                                RTKConnection.useCommand = false;
                                            }
                                        });
                                    } else {

                                        hardwareUpdateService.startUpdateOldHost(new CommonCallBack() {
                                            @Override
                                            public void success(Object result) {
                                                String s = result.toString();
                                                if (StringUtils.isEmpty(s)) {

                                                } else {
                                                    callBack.success("");
                                                    activity.runOnUiThread(() ->hardwareUpdateDialog.showUpdateSuccessDialog(deviceUpdateBean));
                                                }
                                            }

                                            @Override
                                            public void fail(String error) {
                                                activity.runOnUiThread(() -> hardwareUpdateDialog.showUpdateFailDialog(null));
                                            }
                                        });

                                    }
                                } else {
                                    LoadDialog.dismiss(activity);
                                    activity.runOnUiThread(() -> hardwareUpdateDialog.showUpdateFailDialog(null));
                                }
                            }

                            @Override
                            public void fail(String error) {
                                LoadDialog.dismiss(activity);
                                activity.runOnUiThread(() -> MessageBox.show(activity, error));
                            }
                        });
                    }
                });
            }

            @Override
            public void fail(String error) {
                LoadDialog.dismiss(activity);
            }
        });
    }
}
